<?php
/**
 * Description: 申论 - 切磋互评(评论)作业模块
 * User: devforma
 * Date: 16/5/26
 * Time: 12:05
 */

require_once __DIR__ . '/ProcessExerciseBase.class.php';

class HupingPostilModule extends ProcessExerciseBase {

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 9;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        //获取题目和材料
        $questionInfo = $cmsdb->getRow('SELECT `id`, `question`, `answer`, `parent` FROM `original_ztk_shenlun_questions` WHERE `id`=:id', array(':id' => $this->questionIds[0]));
        $materialInfo = $cmsdb->getRow('SELECT `id`, `notice`, `information` FROM `original_ztk_shenlun_questions` WHERE `id`=:id', array(':id' => $questionInfo->parent));

        $this->data['question'] = array(
            'question_id' => (int)$questionInfo->id,
            'notice'      => $materialInfo->notice,
            'material'    => $materialInfo->information,
            'question'    => $questionInfo->question,
            'answer'      => $questionInfo->answer
        );
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询评论记录
        $sql = 'SELECT * FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid LIMIT 1';
        $reviewRecord = $uddb->getRow($sql, array(':uid' => $this->userId, ':eid' => $this->exerciseId));

        if (empty($reviewRecord)) { //还没有评论记录,随机选取其他用户的答题记录

            //该作业需要评论的作业id
            $originalExerciseId = $this->exerciseInfo->constraint_ids;

            //查询未被评论过的作业答题记录
            $hupingExerciseIds = $this->getHupingExerciseIds($originalExerciseId);
            $sql = 'SELECT a.id, a.user_id, a.action_time, a.user_answer FROM `history_primary_question_review` AS a WHERE a.user_id!='.$this->userId.' AND a.exercise_id='.$originalExerciseId.' AND NOT EXISTS (SELECT 1 FROM `history_primary_question_review` AS b where b.exercise_id in ('.$hupingExerciseIds.') and b.question_id=a.id)';
            $originalRecords = (array)$uddb->getResults($sql);

            //如果所有记录都被评论过,随机选取
            if (empty($originalRecords)) {
                $sql = 'SELECT `id`, `user_id`, `action_time`, `user_answer` FROM `history_primary_question_review` WHERE `exercise_id`=:eid AND `user_id`!=:uid';
                $originalRecords = (array)$uddb->getResults($sql, array(':eid' => $originalExerciseId, ':uid' => $this->userId));
            }

            if (!empty($originalRecords)) {

                //获取该用户评论过的所有记录
                $alreadyReviewedRecordIds = (array)$uddb->getCol('SELECT `question_id` FROM `history_primary_question_review` WHERE `reviewer_id`=:uid AND `reviewer_type`=1',
                    array(':uid' => $this->userId));

                //随机选取一个答题记录,需要排除已经评论过的记录
                shuffle($originalRecords);
                $randomOriginalRecord = $originalRecords[0];
                if (in_array($randomOriginalRecord->id, $alreadyReviewedRecordIds, true)) { //随机出来的正好已经评论过了
                    $randomOriginalRecord = isset($originalRecords[1]) ? $originalRecords[1] : null;
                }

                if (!empty($randomOriginalRecord)) {
                    //设置用户答案字段
                    $this->data['user_answer'] = array(
                        'user_record' => array(
                            'record_id'   => (int)$randomOriginalRecord->id,                         //被评论的作业的答题记录id
                            'user_info'   => $this->getStudentInfo($randomOriginalRecord->user_id),  //被评论的用户信息
                            'submit_time' => $randomOriginalRecord->action_time,                     //被评论的答题记录提交时间
                            'images'      => explode('#', $randomOriginalRecord->user_answer)        //被评论的答题记录内容
                        )
                    );
                } else {
                    $this->data['user_answer'] = new stdClass();
                }
            }

        } else { //有评论记录,取评论数据
            $content = array();

            //查询被评论学生的答案,评论记录的question_id为被评论的答题记录id
            $sql = 'SELECT * FROM `history_primary_question_review` WHERE `id`=:record_id';
            $originalRecord = $uddb->getRow($sql, array(':record_id' => $reviewRecord->question_id));

            //被评论的原始答题信息
            $content['user_record'] = array(
                'record_id'   => (int)$originalRecord->id,                       //被评论的作业的答题记录id
                'user_info'   => $this->getStudentInfo($originalRecord->user_id),  //被评论的用户信息
                'submit_time' => $originalRecord->action_time,                   //被评论的答题记录提交时间
                'images'      => explode('#', $originalRecord->user_answer)      //被评论的答题记录内容
            );

            //我的评论
            $content['my_postil'] = array(
                'review_level'  => $reviewRecord->review_content,                  //评论级别
                'review_time'   => $reviewRecord->review_time,                     //评论时间
                'review_postil' => nl2br((string)$reviewRecord->review_postil)     //评论内容
            );

            //设置用户答案字段
            $this->data['user_answer'] = $content;
        }
    }

    /**
     * 获取学生信息
     *
     * @param int $userId 用户id
     * @return array
     */
    private function getStudentInfo($userId) {
        global $uddb;

        $info = $uddb->getRow('SELECT `nickname`, `avatar` FROM `user_social_info` WHERE `user_id`=:uid', array(':uid' => $userId));

        //兼容每日一题的头像保存url
        if (!empty($info->avatar) && strpos($info->avatar, 'http://') === false) {
            $info->avatar = 'http://edu.appublisher.com/user-images/avatar/'.$info->avatar;
        }

        return array(
            'user_id'  => (int)$userId,
            'nickname' => $info->nickname,
            'avatar'   => (string)$info->avatar
        );
    }

    /**
     * 校验参数
     *
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['postil']) && !empty($args['record_id']) && !empty($args['level'])) { //评论内容和被评论的用户答题记录id
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 设置作业状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 1; //已完成
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 保存作业答题记录及统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        //插入新纪录
        $uddb->insert('history_primary_question_review', array(
            'exercise_id'   => $this->exerciseId,              //本次作业id
            'question_id'   => $this->submitArgs['record_id'], //被评论的作业对应的答题记录id
            'user_id'       => $this->userId,                  //用户id
            'action_time'   => $this->now,                     //提交时间
            'reviewer_id'   => $this->userId,                  //评论者id
            'review_time'   => $this->now,                     //评论时间
            'reviewer_type' => 1,                              //评论类型(学生)
            'review_postil' => $this->submitArgs['postil'],    //评论内容
            'review_content'=> $this->submitArgs['level']      //评论级别
        ));

        $this->submitExerciseRecord['summary'] = '';
    }

    /**
     * 创建消息
     */
    protected function doExtra() {
        global $uddb;

        $record = $uddb->getRow('SELECT `user_id`, `exercise_id` FROM `history_primary_question_review` WHERE `id`=:record_id', array(':record_id' => $this->submitArgs['record_id']));
        $uddb->insert('history_user_notification', array(
            'user_id'             => $record->user_id,
            'primary_exercise_id' => $record->exercise_id,
            'type'                => 2,
            'sender_id'           => $this->userId,
            'send_time'           => $this->now,
            'status'              => 0
        ));
    }

    /**
     * 根据单体突破作业获取点评作业
     *
     * @param int $dantiId 单题突破作业id
     * @return string
     */
    private function getHupingExerciseIds($dantiId) {
        global $cmsdb;

        $cacheKey = 'vip:func:getHupingExerciseIds'.$dantiId;
        if (($ids = cacheGet($cacheKey)) == null) {
            $ids = $cmsdb->getCol('SELECT `id` FROM `data_primary_exercise` WHERE `constraint_ids`=:danti', [':danti' => $dantiId]);

            if (empty($ids)) return '';

            cacheAdd($cacheKey, implode(',', $ids), 24*60*60);
        }

        return $ids;
    }
}